package com.sicnu.resources.controller;

import com.qcloud.cos.model.COSObjectSummary;
import com.sicnu.resources.bean.res.Result;
import com.sicnu.resources.service.CosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * @author 怨九己
 */
@RestController
@RequestMapping("/api/cos")
public class CosController {

    private final CosService cosService;

    @Value("${oss.bucket-name}")
    private String bucketName;

    @Autowired
    public CosController(CosService objectStorageService) {
        this.cosService = objectStorageService;
    }

    @PostMapping("")
    public Result<String> uploadObject(
            @RequestParam String key,
            @RequestParam MultipartFile file) throws IOException {
        String result = cosService.uploadObject(bucketName, key, file);
        if ("上传成功".equals(result)) {
            return Result.buildSuccess(result);
        } else {
            return Result.buildFailure(result);
        }
    }

    @DeleteMapping("")
    public Result<String> deleteObject(
            @RequestParam String key) {
        cosService.deleteObject(bucketName, key);
        return Result.buildSuccess("File deleted successfully");
    }

    @GetMapping("")
    public Result<URL> playObject(
            @RequestParam String key) {
        URL url = cosService.generatePresignedUrl(bucketName, key);
        if (url != null) {
            return Result.buildSuccess(url);
        } else {
            return Result.buildFailure("Failed to generate presigned URL");
        }
    }

    @GetMapping("/object")
    public Result<List<COSObjectSummary>> searchObjects(
            @RequestParam String key) {
        List<COSObjectSummary> objects =
                cosService.searchObjects(bucketName, key);
        if (objects != null) {
            return Result.buildSuccess(objects, (long) objects.size());
        } else {
            return Result.buildFailure("Failed to search objects");
        }
    }

    @PostMapping("/file")
    public Result<String> uploadLargeFile(
            @RequestParam String key,
            @RequestParam MultipartFile file)
            throws IOException {
        // 将 MultipartFile 转换为 File
        File tempFile = File.createTempFile("temp", null);
        file.transferTo(tempFile);
        // 调用断点续传服务
        String result = cosService.uploadLargeFile(bucketName, key, tempFile);
        // 删除临时文件
        tempFile.delete();
        if ("上传成功".equals(result)) {
            return Result.buildSuccess(result);
        } else {
            return Result.buildFailure(result);
        }
    }
}